package com.unisedu.weapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.unisedu.weapp.entity.Student;
import com.unisedu.weapp.repository.StudentRepository;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @author hanbing
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    private final StudentRepository studentRepository;

    @Autowired
    public StudentController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @PostMapping
    public ResponseEntity register(Student student){
        System.out.println(student.toString());
        studentRepository.addUser(student);
        return new ResponseEntity<>("ok", HttpStatus.OK);
    }

    @GetMapping("/auth/code")
    public ResponseEntity authCode(String code) throws IOException {
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx35ea369e7e926188&secret=0f566068c13a7461409c09b66d4d8628&js_code="+code+"&grant_type=authorization_code";
        Document dom = Jsoup.connect(url).timeout(30000).get();
        String body = dom.body().html();
        JSONObject json = JSONObject.parseObject(body);
        return new ResponseEntity<>(json, HttpStatus.OK);
    }

    @GetMapping("/classes")
    public ResponseEntity getMyClasses(String openid){
        List<String> classes = studentRepository.getMyClasses(openid);
        return new ResponseEntity<>(classes, HttpStatus.OK);
    }

    @PostMapping("signup")
    public ResponseEntity signUp(String className, String openid){
        String result = studentRepository.signUp(className, openid);
        if(result == null){
            return new ResponseEntity(HttpStatus.NO_CONTENT);
        }else{
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
    }

    @GetMapping("/{openid}")
    public ResponseEntity isSignUp(@PathVariable("openid") String openid){
        System.out.println(openid);
        if(studentRepository.isSignUp(openid)){
            return new ResponseEntity<>( HttpStatus.OK);
        }else{
            return new ResponseEntity<>( HttpStatus.NO_CONTENT);
        }


    }

}
